﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SIG.Model;
using SIG.Service;
using SIG.Model.ViewModel.Back;
using SIG.Basic.Helper;
using PagedList;
using SIG.Model.DTO;
using SIG.WebUI.Areas.Admin.Models;
using AutoMapper;
using SIG.Model.Extensions;

namespace SIG.WebUI.Areas.Admin.Controllers
{
    [Authorize(Roles = "创始人,管理员")]
    public class PagesController : AdminController
    {
        private readonly IPageService _pageService;
        private readonly IPageMetaService _pageMetaService;
        public PagesController(IPageService pageService, IPageMetaService pageMetaService)
        {
            _pageService = pageService;
            _pageMetaService = pageMetaService;

            AjaxResult = new Model.ViewModel.AjaxResultVM();
        }

        // GET: Admin/Pages
        public ActionResult Index(int? page, string title)
        {
            var pageVM = new PageSearchVM();
            pageVM.Title = title;  
            pageVM.PageIndex = (page ?? 1) - 1;
            pageVM.PageSize = Site.Settings.Page.PageSize;
            pageVM.Pages = _pageService.SearchPages(pageVM.PageIndex, pageVM.PageSize, pageVM.Title);
            pageVM.TotalCount = _pageService.SearchPagesCount(pageVM.Title);

            var pagesAsIPagedList = new StaticPagedList<Page>(pageVM.Pages, pageVM.PageIndex + 1, pageVM.PageSize, pageVM.TotalCount);
            ViewBag.OnePageOfPages = pagesAsIPagedList;
          
            return View(pageVM);
            
        }

        // GET: Admin/Pages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            
            Page page = _pageService.GetById(id);
            if (page == null)
            {
                return HttpNotFound();
            }
            return View(page);
        }

        // GET: Admin/Pages/Create
        public ActionResult Create()
        {

            PagePageMetaDTO page = new PagePageMetaDTO()
            {
                //Id = 0,
                Active = true
            };
            return View(page);
        }

        // POST: Admin/Pages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult Create([Bind(Include = "Id,Title,Body,PathName,Description,Keywords,Active")] PagePageMetaDTO page)
        {
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));

                AjaxResult.SetError(message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }


            try
            {
                page.ViewCount = 0;
                var newPage = Mapper.Map<PagePageMetaDTO, Page>(page);

                _pageService.Create(newPage);

                if (!string.IsNullOrEmpty(page.Keywords) || !string.IsNullOrEmpty(page.Description))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newPage.Id,
                        Keyword = page.Keywords.Replace('，', ','),
                        Description = page.Description,
                        ModelType = ModelType.PAGE
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AjaxResult.Message = String.Format(Site.AlertCreateSuccess, Site.Settings.Page.SetName);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AjaxResult.SetError(er.Message);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }
                   
        }

        // GET: Admin/Pages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Page page = _pageService.GetById(id);

            if (page == null)
            {
                return HttpNotFound();
            }

            var editPage = Mapper.Map<Page, PagePageMetaDTO>(page);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.PAGE, editPage.Id);
            if (pageMeta != null)
            {
                editPage.Keywords = pageMeta.Keyword;
                editPage.Description = pageMeta.Description;
            }
                       
            return View(editPage);
           
        }

        // POST: Admin/Pages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit([Bind(Include = "Id,Title,Body,PathName,Description,Keywords,ViewCount,Active")] PagePageMetaDTO page)
        {
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));

                AjaxResult.SetError(message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }

            try
            {
                var editPage = Mapper.Map<PagePageMetaDTO, Page>(page);

                _pageService.Update(editPage);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.PAGE, editPage.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(page.Keywords) || !string.IsNullOrEmpty(page.Description))
                {

                    pageMeta.ObjectId = page.Id;
                    pageMeta.Keyword = page.Keywords.Replace('，',',');
                    pageMeta.Description = page.Description;
                    pageMeta.ModelType = ModelType.PAGE;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AjaxResult.Message = String.Format(Site.AlertUpdateSuccess, Site.Settings.Page.SetName);
                return Json(AjaxResult, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AjaxResult.SetError(er.Message);

                return Json(AjaxResult, JsonRequestBehavior.DenyGet);
            }

          
        }

        // GET: Admin/Pages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Page page = _pageService.GetById(id);
            if (page == null)
            {
                return HttpNotFound();
            }
            return View(page);
        }

        // POST: Admin/Pages/Delete/5
        [HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        public JsonResult DeleteConfirmed(int id)
        {
            Page page = _pageService.GetById(id);           
            if (page != null)
            {
                _pageService.Delete(page);
                return Json(true, JsonRequestBehavior.DenyGet);
            }
            return Json(false, JsonRequestBehavior.DenyGet);
          
        }

        public JsonResult IsPathNameUnique(string PathName, int? Id)
        {
            return !IsExist(PathName, Id)
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }
        public bool IsExist(string PathName, int? id)
        {
            var wType = _pageService.FindBy(w => w.PathName == PathName && w.Id != id).ToList();
            if (wType.Count > 0)
                return true;
            return false;
        }
    }
}
